package com.qianke.common;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.MalformedURLException;
import java.net.URL;

public class WebUtils {

    private static final Logger logger = LoggerFactory.getLogger(WebUtils.class);

    public static boolean isXhr(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }

    public static void crossOrigin(HttpServletRequest request, HttpServletResponse response) {

        try {
            if (!response.containsHeader("Access-Control-Allow-Origin")) {
                response.addHeader("Access-Control-Allow-Origin", getRefererHost(request));
            }
            if (!response.containsHeader("Access-Control-Allow-Credentials")) {
                response.addHeader("Access-Control-Allow-Credentials", "true");
            }
            if (!response.containsHeader("Access-Control-Allow-Methods")) {
                response.addHeader("Access-Control-Allow-Methods", "*");
            }

        } catch (Exception e) {
            logger.warn("", e);
        }
    }

    public static String getRefererHost(HttpServletRequest request) {
        try {
            String origin = request.getHeader("referer");
            URL url = new URL(origin);
            if (url.getPort() > 0) {
                return url.getProtocol() + "://" + url.getHost() + ":" + url.getPort();
            }
            return url.getProtocol() + "://" + url.getHost();

        } catch (MalformedURLException e) {
            logger.warn("", e);
        }

        return StringUtils.EMPTY;
    }


    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader("X-Forwarded-For");
        if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值，第一个为真实IP。
            int index = ip.indexOf(',');
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        } else {
            return request.getRemoteAddr();
        }
    }

}
